/**
 * Copyright (C),2011-2012,北京国电通网络技术有限公司.
 * FileName:	safeguardLoop.cpp
 * Author:		LiYang
 * Version:		V0.1
 * Date:		2011-11-15
 * Description	This file receives data from serial, and put them in list by some fixed format, in order to dispose
 */

/**
 * History:
 * 		Author		date		Version		Description
 */

#include "upLoop.h"
#include "../sqlite/sqlite.h"

///global variables used in this file
unsigned char g_buf2[RECVDATA_NUM];

extern struct StSerialFD g_serialFD;
extern struct StLED g_LED;
extern int setLed_ON;
extern int setLed_OFF;

/***safeguardLoopHandler() brief loop control up-stream dispose
 * param void
 *
 * retval void
 ***/
void safeguardHandler(void)
{
	PRINTOUT("%s","In safeguardHandler()");
#ifdef DEBUG_ARM
	int l_maxfd=0;									///l_maxfd:the max number of file descriptor +1.
	fd_set l_readset;								///read set of file descriptor.

	l_maxfd=g_serialFD.st_serial2;
	l_maxfd += 1;
	FD_ZERO(&l_readset);							///clear l_readset
	FD_SET(g_serialFD.st_serial2,&l_readset);
	while(FD_ISSET(g_serialFD.st_serial2,&l_readset))
	{
		if(select(l_maxfd,&l_readset,NULL,NULL,NULL)<0)
		{
			ERROROUT("no select!");
			///if failed, set them into corresponding set again and continue
			FD_ZERO(&l_readset);
			FD_SET(g_serialFD.st_serial2,&l_readset);
			continue;
		}
		else
		{
			if(FD_ISSET(g_serialFD.st_serial2,&l_readset))							///safeguard
			{
				PRINTOUT("%s","read from 'g_serial2'--ttyS2(serial4)!");
				myDelay(RECEIVEDELAY*10);
				memset(g_buf2,0,RECVDATA_NUM);
				if(read(g_serialFD.st_serial2,g_buf2,RECVDATA_NUM)==-1)				///read  data from ttyS2
				{
					ERROROUT("read from ttyS2(serial42) failed!");
					tcflush(g_serialFD.st_serial2,TCIFLUSH);						///flushes data received but not read.
					continue;														///if have error, just ignore, read next.
				}
				if(g_LED.st_mod3>=0)
				{
					#ifdef FREESCALE
						write(g_LED.st_mod3,&setLed_ON,1);
						myDelay(100);
						write(g_LED.st_mod3,&setLed_OFF,1);
					#else
						ioctl(g_LED.st_mod3, SET_LED_ON, NULL);
						myDelay(100);
						ioctl(g_LED.st_mod3, SET_LED_OFF, NULL);
					#endif
				}
				if(insertRecv(g_buf2)==-1)											///up direction protocol switch.
				{
					ERROROUT("insertRecv() failed!");
					continue;														///if have error, just ignore.
				}
			}
		}
	}
#endif
}
